package com.tnsw.facebookautoliker.services;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimerTask;

import com.tnsw.coreutils.MyLog;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.database.FriendsPost;
import com.tnsw.facebookautoliker.helper.command.FQLBase;
import com.tnsw.facebookautoliker.helper.command.GetSelfPost;
import com.tnsw.facebookautoliker.helper.command.LikeManager;

import android.content.Context;

public class AutoLikerTimerTask extends TimerTask {

	public static int MAX_RECORD_PER_FETCH = 500;
	
	private String tag = "AutoLikeTimerTask";
	private Context context;
	private AutoLikerService service;
	private long lastExecute = 0;
	
	private boolean _isPause = true;
	private DBManager dbm;
	private LikeManager lm;
	
	private long stopCondition = 0;  // The latest updated_time or created_time for latest query
		
	public AutoLikerTimerTask(Context context, AutoLikerService service) {
		this.context = context;
		this.service = service;
		this.dbm = DBManager.getInstance(context);
		
		this.lm = new LikeManager(this.context, this.service.getSelfInfo());
	}
	
	@Override
	public void run() {
		this.lastExecute = System.currentTimeMillis();
		MyLog.d(tag, "run()");
		
		if (this._isPause == false) {
			this.execute("me()", null);
			this.likeOnWaitList();
			GetSelfPost gsp = new GetSelfPost(this.context);
			gsp.execute();
		} else {
			MyLog.d(tag, "--> paused!");
		}
		
	}
	
	public void likeOnWaitList() {
		MyLog.d(tag, "likeOnWaitList()");
		this.service = AutoLikerService.getInstance();
		
		ArrayList<FriendsPost> arrWaitLike = this.service.getArrWaitLike();
		
		if (arrWaitLike != null) {
			MyLog.d(tag, "count=" + arrWaitLike.size());
			if (arrWaitLike.size() > 0) {
				FriendsPost fp = arrWaitLike.get(0);
				this.lm.doLike(fp.post_id, null, null);
				
			}
		}		
	}
	
	private long getLast24hrSec() {
		long sec = 0;
		
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		c.add(Calendar.HOUR, -24);
		sec = c.getTimeInMillis() / 1000;
		
		return(sec);
	}
	
	private long[] getLatestFromDB() {
		long[] l = new long[] {this.getLast24hrSec(), this.getLast24hrSec()};
		ArrayList<Object> a = this.dbm.getRawRecords("select max(created_time), max(updated_time) from friends_post", null, 0);
		if (a != null) {
			ArrayList<Object> aa = (ArrayList<Object>) a.get(0);
			if (aa.get(0) != null) {
				l[0] = (Long) aa.get(0);
				l[1] = (Long) aa.get(1);
			} 
		}
		
		return(l);
	}
	
	public long getStopCondition() {
		return(this.stopCondition);
	}
		
	public void execute(String source_id, String ownerTag) {
		FQLBase fqlb;
		long l = this.getLast24hrSec();
		
		long[] l2 = this.getLatestFromDB();
		long maxCreatedTime = l2[0];
		long maxUpdatedTime = l2[1];
		
		if (maxUpdatedTime > l) {
			// latest updated_time is less than 24 hours, use this instead
			l = maxCreatedTime;
			MyLog.d(tag, "execute using max(created_time) from friends_post");
		} else {
			MyLog.d(tag, "execute using last 24 hours");
		}
		
		this.stopCondition = l;
		
		String fql = "SELECT updated_time, likes, attachment, created_time, description, message, type, app_id, attachment, message, post_id, actor_id, like_info FROM stream WHERE filter_key in (SELECT filter_key FROM stream_filter WHERE uid=" + source_id + " AND type = 'newsfeed') and created_time > " + String.valueOf(l);
		fql = "SELECT updated_time, likes, attachment, created_time, description, message, type, app_id, attachment, message, post_id, actor_id, like_info FROM stream WHERE filter_key in (SELECT filter_key FROM stream_filter WHERE uid=" + source_id + " AND type = 'newsfeed')";
		fqlb = new FQLBase(context, fql, null);
		
		fqlb.setOrderCondition(" order by created_time desc ");
		//fqlb.setPagingColumn("updated_time");
		fqlb.setPagingColumn(null);
		fqlb.setLimit(50);
		fqlb.setMaxRecord(MAX_RECORD_PER_FETCH);
		fqlb.setApplyCounter(false);
		
		fqlb.setFQLInterface(service);
		fqlb.setTag("command", "timer");
		fqlb.setTag("source_id", source_id);
		
		if (ownerTag != null) {
			fqlb.setTag("owner_tag", ownerTag);
		}
		
		fqlb.execute();
	}
	
	public void pause() {
		this._isPause = true;
		this.service.getSelfInfo().timer_enable = "N";
		
		this.dbm.updateRecordByPrimarykey("self_info", this.service.getSelfInfo(), true);
		
	}
	
	public void resume() {
		this._isPause = false;
		this.service.getSelfInfo().timer_enable = "Y";
		
		this.dbm.updateRecordByPrimarykey("self_info", this.service.getSelfInfo(), true);
	}
	
	public boolean isPause() {
		return(this._isPause);
	}
		
	public long getLastExecute() {
		return(this.lastExecute);
	}

}
